package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.igas.bomp.facade.BompMchntInspectService;
import cc.rengu.igas.bomp.facade.bean.NeedInspectMchntInfoBean;
import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.InspectTaskDetail;
import cc.rengu.redp.bizimpl.upmp.domain.InspectTaskInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntBaseInfo;
import cc.rengu.redp.bizimpl.upmp.service.IInspectTaskInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpBMchntBaseInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysSeqService;
import cc.rengu.redp.bizimpl.upmp.service.impl.AlpaySpecialFeeService;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.*;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Api(tags = "商户管理:巡检任务信息管理")
@RestController
@RequestMapping(value = "/admin/merParam/inspectTaskInfo")
public class InspectTaskInfoController extends BaseController {
    @Autowired
    private IInspectTaskInfoService inspectTaskInfoService;
    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
//// @DubboReference(version = "2.2.0", url = "dubbo://172.17.100.9:62132", check = false)
    private BompMchntInspectService mchntInspectService;

    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;

    @Autowired
    private AlpaySpecialFeeService alpaySpecialFeeService;


    //@RequiresPermissions("inspectTaskInfo:list")
    @GetMapping(value = "/list")


    public Map<String, Object> findByPage(HttpServletRequest request, QueryRequest queryRequest) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        return getDataTable(inspectTaskInfoService.findPageFromBomp(request, queryRequest, user, mchntInspectService, bMchntBaseInfoService.genMerOrder(user.getInstId())));
    }


    //@RequiresPermissions("商户管理:巡检任务信息管理")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public OperationResult editSave(HttpServletRequest request, Model model) {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        String mchntNos = request.getParameter("mchntNos");
        String inspectTaskNo = request.getParameter("inspectTaskNo");
        String inspectTaskType = request.getParameter("inspectTaskType");
        String inspectTaskDesc = request.getParameter("inspectTaskDesc");
        String inspectType = request.getParameter("inspectType");
        String inspectInstId = request.getParameter("inspectInstId");
        String instId = request.getParameter("instId");
        String inspectBeginTime = request.getParameter("inspectBeginTime");
        String inspectEndTime = request.getParameter("inspectEndTime");
        String flag = request.getParameter("flag");
        String saveFlag = request.getParameter("saveFlag");

        if (StringUtils.isBlank(inspectInstId) || !inspectInstId.equals("00")) {
            return OperationResult.buildFailureResult("新增时巡检机构必须选择自主巡检", result);
        }
        /*
        1、生成线上审核巡检任务 巡检状态是 01-巡检待提交，修改之后是 02-待审核，审核后是拒绝或者通过；
        2、生成线下巡检任务 巡检状态是 00 -未巡检，拓展经理从移动端录入巡检结果后，状态为10-已巡检；
        3、生成电话巡检任务  巡检状态是 00 -未巡检，拓展经理从移动端录入巡检结果后，状态为10-已巡检；
        */
        inspectTaskNo = generateCode();
        InspectTaskInfo inspectTaskInfo = new InspectTaskInfo();
        inspectTaskInfo.setInstId(instId);
        inspectTaskInfo.setInspectTaskNo(inspectTaskNo);
        inspectTaskInfo.setInspectTaskDesc(inspectTaskDesc);
        inspectTaskInfo.setInspectTaskType(inspectTaskType);
        inspectTaskInfo.setInspectType(inspectType);
        inspectTaskInfo.setInspectBeginTime(inspectBeginTime);
        inspectTaskInfo.setInspectEndTime(inspectEndTime);
        inspectTaskInfo.setCreateTime(lastUpddt);
        inspectTaskInfo.setOprId(user.getId());
        inspectTaskInfo.setCrtOrgId(user.getOrgCode());
        inspectTaskInfo.setInspectTaskStatus("01");
        inspectTaskInfo.setCrtOrgId(user.getOrgCode());

        // 根据mchntNos 查询所有商户信息，赋值给inspectTaskDetail
        List<InspectTaskDetail> inspectTaskDetails = new ArrayList<>();
        InspectTaskDetail inspectTaskDetail;
        if ("allInspect".equals(flag)) {
            //全部巡检，调联机接口获取商户信息
            List<NeedInspectMchntInfoBean> resultData = inspectTaskInfoService.allNeedInspectMchntListQuery(request, user, mchntInspectService, bMchntBaseInfoService.genMerOrder(user.getInstId()));
            if (null != resultData && resultData.size() > 0) {
                for (NeedInspectMchntInfoBean needInspectMchntInfoBean : resultData) {
                    inspectTaskDetail = new InspectTaskDetail();
                    inspectTaskDetail.setInstId(instId);
                    inspectTaskDetail.setInspectTaskNo(inspectTaskNo);
                    inspectTaskDetail.setMchntNo(needInspectMchntInfoBean.getMchntNo());
                    inspectTaskDetail.setMchntName(needInspectMchntInfoBean.getMchntName());
                    inspectTaskDetail.setMchntBizAddr(needInspectMchntInfoBean.getMchntBizAddr());
                    inspectTaskDetail.setMchntType(needInspectMchntInfoBean.getMchntType());
                    inspectTaskDetail.setIndustryType(needInspectMchntInfoBean.getIndustryType());
                    inspectTaskDetail.setMchntAttr(needInspectMchntInfoBean.getMchntAttr());
                    inspectTaskDetail.setMchntLevel(needInspectMchntInfoBean.getMchntLevel());
                    inspectTaskDetail.setRiskLevel("");
                    inspectTaskDetail.setSignInstId(needInspectMchntInfoBean.getSignInstId());
                    // 自主巡检，填写签约机构
                    inspectTaskDetail.setInspectInstId(inspectTaskDetail.getSignInstId());
                    inspectTaskDetail.setManagerId(needInspectMchntInfoBean.getManagerId());
                    inspectTaskDetail.setManagerName(needInspectMchntInfoBean.getManagerName());
                    inspectTaskDetail.setInspectTaskType(inspectTaskType);
                    inspectTaskDetail.setInspectType(inspectType);
                    if ("10".equals(inspectType)) {
                        // 线上审核巡检
                        inspectTaskDetail.setInspectStatus("01");
                    }
                    if ("20".equals(inspectType) || "00".equals(inspectType)) {
                        // 线下现场巡检
                        inspectTaskDetail.setInspectStatus("00");
                    }
                    inspectTaskDetail.setInspectBeginTime(inspectBeginTime);
                    inspectTaskDetail.setInspectEndTime(inspectEndTime);
                    inspectTaskDetail.setCreateTime(lastUpddt);
                    inspectTaskDetail.setOprId(user.getId());

                    inspectTaskDetails.add(inspectTaskDetail);
                }
            } else {
                return OperationResult.buildSuccessResult("获取商户失败", result);
            }
        } else {
            if (StringUtils.isBlank(mchntNos)) {
                return OperationResult.buildFailureResult("商户号为空", result);
            }
            String[] mchntNoArr = mchntNos.split(",");
            if (mchntNoArr.length <= 0) {
                return OperationResult.buildFailureResult("商户号为空", result);
            }
            for (String mchntNo : mchntNoArr) {
                // 此处商户的属性用查出来的商户对象替换
                UpmpBMchntBaseInfo mchntBaseInfo = bMchntBaseInfoService.findByMchntNo(mchntNo);
                if (null == mchntBaseInfo) {
                    continue;
                }
                inspectTaskDetail = new InspectTaskDetail();
                inspectTaskDetail.setInstId(instId);
                inspectTaskDetail.setInspectTaskNo(inspectTaskNo);
                inspectTaskDetail.setMchntNo(mchntNo);
                inspectTaskDetail.setMchntName(mchntBaseInfo.getMchntName());
                inspectTaskDetail.setMchntBizAddr(mchntBaseInfo.getMchntBizAddr());
                inspectTaskDetail.setMchntType(mchntBaseInfo.getMchntType());
                inspectTaskDetail.setIndustryType(mchntBaseInfo.getIndustryType());
                inspectTaskDetail.setMchntAttr(mchntBaseInfo.getMchntAttr());
                inspectTaskDetail.setMchntLevel(mchntBaseInfo.getMchntLevel());
                inspectTaskDetail.setRiskLevel("");
                inspectTaskDetail.setSignInstId(mchntBaseInfo.getSignInstId());
                // 自主巡检，填写签约机构
                inspectTaskDetail.setInspectInstId(inspectTaskDetail.getSignInstId());
                inspectTaskDetail.setManagerId(mchntBaseInfo.getManagerId());
                inspectTaskDetail.setManagerName(mchntBaseInfo.getManagerName());
                inspectTaskDetail.setInspectTaskType(inspectTaskType);
                inspectTaskDetail.setInspectType(inspectType);
                if ("10".equals(inspectType)) {
                    // 线上审核巡检
                    inspectTaskDetail.setInspectStatus("01");
                }
                if ("20".equals(inspectType) || "00".equals(inspectType)) {
                    // 线下现场巡检
                    inspectTaskDetail.setInspectStatus("00");
                }
                inspectTaskDetail.setInspectBeginTime(inspectBeginTime);
                inspectTaskDetail.setInspectEndTime(inspectEndTime);
                inspectTaskDetail.setCreateTime(lastUpddt);
                inspectTaskDetail.setOprId(user.getId());

                inspectTaskDetails.add(inspectTaskDetail);
            }
        }
        inspectTaskInfoService.saveData(inspectTaskInfo, inspectTaskDetails, request, saveFlag);

        if ("allInspect".equals(flag)) {
            return OperationResult.buildSuccessResult("全部生成巡检任务异步执行中，请稍后查看结果", result);
        }
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }


    //@RequiresPermissions("商户管理:巡检任务信息管理")
    @RequestMapping(value = "/sendInspectNotice", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required =true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "inspectTaskNo", value = "巡检任务编号",required =true,  dataType = "String")
    })
    public OperationResult sendInspectNotice(HttpServletRequest request) {
        System.out.println( request.getParameter("instId")+"**  ** "+request.getParameter("inspectTaskNo"));
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String instId = request.getParameter("instId") == null ? "0" : request.getParameter("instId");
        String inspectTaskNo = request.getParameter("inspectTaskNo") == null ? "0" : request.getParameter("inspectTaskNo");
        InspectTaskInfo inspectTaskInfo = inspectTaskInfoService.selectByinstIdAndinspectTaskNo(instId, inspectTaskNo);
        System.out.println(inspectTaskInfo+"*****");
        if (null == inspectTaskInfo) {
            return OperationResult.buildFailureResult("根据编号查询巡检任务信息失败", result);
        }
        // 发送巡检通知
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        return inspectTaskInfoService.mchntInspectNotice(inspectTaskInfo.getInspectTaskNo(), bMchntBaseInfoService.genMerOrder(user.getInstId()), mchntInspectService,instId);
    }


    //@RequiresPermissions("商户管理:巡检任务信息管理")
    @GetMapping(value = "/mchntList")

    public Map<String, Object> mchntList(HttpServletRequest request, QueryRequest queryRequest) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        return getDataTable(inspectTaskInfoService.needInspectMchntListQuery(request, queryRequest, user, mchntInspectService, bMchntBaseInfoService.genMerOrder(user.getInstId())));
    }

    //@RequiresPermissions("商户管理:巡检任务信息管理")
    @GetMapping(value = "/spotCheckMchntList")

    public Map<String, Object> spotCheckMchntList(HttpServletRequest request, QueryRequest queryRequest) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        return getDataTable(inspectTaskInfoService.needInspectMchntListQuery(request, queryRequest, user, mchntInspectService, bMchntBaseInfoService.genMerOrder(user.getInstId())));
    }


    //@RequiresPermissions("商户管理:巡检任务信息管理")
    @GetMapping(value = "/dealLowMchntList")

    public Map<String, Object> dealLowMchntList(HttpServletRequest request, QueryRequest queryRequest) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        return getDataTable(inspectTaskInfoService.needInspectMchntListQuery(request, queryRequest, user, mchntInspectService, bMchntBaseInfoService.genMerOrder(user.getInstId())));
    }

    //@RequiresPermissions("商户管理:巡检任务信息管理")
    @GetMapping(value = "/riskMchntList")

    public Map<String, Object> riskMchntList(HttpServletRequest request, QueryRequest queryRequest) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        return getDataTable(inspectTaskInfoService.needInspectMchntListQuery(request, queryRequest, user, mchntInspectService, bMchntBaseInfoService.genMerOrder(user.getInstId())));
    }

    //@RequiresPermissions("商户管理:巡检任务信息管理")
    @GetMapping(value = "/expandMchntList")

    public Map<String, Object> expandMchntList(HttpServletRequest request, QueryRequest queryRequest) throws RedpException {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        return getDataTable(inspectTaskInfoService.needInspectMchntListQuery(request, queryRequest, user, mchntInspectService, bMchntBaseInfoService.genMerOrder(user.getInstId())));
    }

    /*========================================================================================*/

    //@RequiresPermissions("商户管理:巡检任务信息管理")
    @DeleteMapping("/{ids}")
    @ApiImplicitParam(paramType = "path", name = "ids", value = "id主键，逗号隔开", required = true, dataType = "String")
    public void delete(@NotBlank(message = "{required}") @PathVariable String ids) throws RedpException {
        try {
            this.inspectTaskInfoService.getBaseMapper().deleteBatchIds(Arrays.asList(ids.split(StringPool.COMMA)));
        } catch (Exception e) {
            String message = "删除失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    /**
     * 系统生成巡检任务编号（格式：XJ + 6位编号）
     *
     * @return
     */
    private String generateCode() {
        // 固定入参
        String common = "COMM_PARAM_CODE";
        // 巡检任务编码前缀：XJ
        String prefix = BusinessContainer.InspectTask_PREFIX;
        String instId = upmpSysParamService.getById(UpmpConstant.IGAS_DEFAULT_INST_ID).getPrimaryValue();
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService, instId);
        // 生成序列号
        String serialNumber = upmpSysSeqService.updateParamValue(common, prefix, channelId);
        // 编码：XJ + 6位顺序编号
        return prefix + String.format("%06d", Integer.parseInt(serialNumber));
    }
}
